<?php
/*
  * @author 小白 <chuanwei1234@163.com>  
  * @QQ 86844077  
  * @date 2013-07-20
*/

function set_title($arr,$len,$luostr="",$showziduan=""){
	$restr="";
	$restr2="";
	$len=intval($len);
	if (trim($showziduan)==""){
		$showziduan="title";
	}
	if (is_array($arr)){
		if ($arr[titlecolor]!=""){
		  $restr2.=" color:$arr[titlecolor];";
		}
		switch ($arr["fonttype"]){
		  case "1":
		  $restr2.=" font-weight:bold;";
		  break;
		  case "2":
		  $restr2.=" font-style: italic;";
		  break;
		  case "3":
		  $restr2.=" font-weight:bold; font-style: italic;";
		  break;
		  }
		
		if ($len>0){
			$restr.=wordscut($arr[$showziduan],$len,$luostr);
		}else{
			$restr.=$arr[$showziduan];
		}
		if (trim($restr2)!=""){
		$restr="<font style=\"".$restr2."\">".$restr."</font>";
		}
	}
	return $restr;
}


function showdialog($str){
      echo '<table border="0" cellspacing="1" cellpadding="3" align="center"><tr><td align="right"><img src="/images/t.jpg" /></td><td align="left"><span style="font-size:14px;">'.$str.'</span></td></tr><tr><td colspan="2" height="25" align="center"><input type="button" name="c" value="确 定" class="botton_s" onclick="P.cancel();"/></td></tr></table>';
}

//获取IP地址详情
function get_ip_info($ip){
	$iparr="";
	if ($ip!=""){
		$pageurl="http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=php&ip=".$ip;
		$WebContent=@file_get_contents($pageurl);
		if ($WebContent!=""){
			$iparr=explode("	",$WebContent);
			if ($iparr[0]!=1){$iparr="";}
		}
	}
	return $iparr;
}
//-----微信公众平台---------------------------------------------
function wx_token(){
	global $APPID,$APPSECRET,$db;
	$getstr=file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$APPID}&secret={$APPSECRET}");
	$getinfo=json_decode($getstr,true);
	if (trim($getinfo["errcode"])==""){
		$info=$getinfo;
	}
	else{
		echo "获取微信公众平台失败";
		exit();
	}
	return $info;
}
function wx_get_token(){
	global $db;
	$token="";
	$tokeninfo=$db->getinfo("select * from wx_token limit 1");
	if (!is_array($tokeninfo)){
		$tokeninfo=wx_token();
		$token=$tokeninfo["access_token"];
		$nowdate=date("Y-m-d H:i:s");
		$db->excu("insert into wx_token(token,gettime)values('".$token."','".date("Y-m-d H:i:s",strtotime("$nowdate + 7100 second"))."')");
	}
	else{
		$nowdate=date("Y-m-d H:i:s");
		$nowdate2=strtotime($nowdate);
		if ($nowdate2>=strtotime($tokeninfo["gettime"])){
			$tokeninfo=wx_token();
			$token=$tokeninfo["access_token"];
			$nowdate=date("Y-m-d H:i:s");
			$db->excu("update wx_token set token='".$token."',gettime='".date("Y-m-d H:i:s",strtotime("$nowdate + 7000 second"))."'");
		}
		else{
			$token=$tokeninfo["token"];
		}
	}
	return $token;
}
function wx_get_userinfo($openid){
	$uinfo="";
	$token=wx_get_token();
	if (trim($token)!="" and trim($openid)!=""){
		$getstr=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}");
		$getinfo=json_decode($getstr,true);
		if (trim($getinfo["errcode"])==""){
			$uinfo=$getinfo;
		}
	}
	return $uinfo;
}

//删除微信菜单
function wx_menu_delete(){
	$restr=false;
	$token=wx_get_token();
	if (trim($token)!=""){
		$getstr=file_get_contents("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$token}");
		$getinfo=json_decode($getstr,true);
		if (trim($getinfo["errcode"])==0){
			$restr=true;
		}
	}
	return $restr;
}
//更新微信菜单
function wx_menu_update($menustr){
	$restr=false;
	if (trim($menustr)!=""){
		$token=wx_get_token();
//		echo "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$token}<br>";
//		echo $menustr;
//		exit();
		$getstr=post("https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$token}", $menustr);
		$getinfo=json_decode($getstr,true);
		if (trim($getinfo["errcode"])==0){
			$restr=true;
		}
	}
	return $restr;
}

function wx_update_userinfo($userid="",$weixinid=""){
	global $db,$webdb;
	if ($webdb["weixin_vpptype"]!=1){
		return false;
	}
	if (trim($userid)!=""){
		$rsdb=$db->getinfo("select * from mx_user where id='$userid' order by id limit 1");
	}
	elseif (trim($weixinid)!=""){
		$rsdb=$db->getinfo("select * from mx_user where weixinid='$weixinid' order by id limit 1");
	}
	else{
		return false;
	}
	if (is_array($rsdb)){
		$wxuserinfo=wx_get_userinfo($rsdb["weixinid"]);
		if (is_array($wxuserinfo)){
			$wxuserinfo["nickname"]=str_replace("□","",$wxuserinfo["nickname"]);
			if ($wxuserinfo["subscribe"]==0){
				$files=array(
				"isguanzhu"=>$wxuserinfo["subscribe"],
				"istongbu" =>0
				);
			}
			else{
				$files=array(
				"nicheng"=>$wxuserinfo["nickname"],
				"sex"=>$wxuserinfo["sex"],
				"wx_shi"=>$wxuserinfo["city"],
				"wx_guo"=>$wxuserinfo["country"],
				"wx_sheng"=>$wxuserinfo["province"],
				"wx_language"=>$wxuserinfo["language"],
				"faceurl"=>$wxuserinfo["headimgurl"],
				"isguanzhu"=>$wxuserinfo["subscribe"],
				"guandate"=>date("Y-m-d H:i:s",$wxuserinfo["subscribe_time"]),
				"istongbu" =>1
				);
			}
			//if ($rsdb["id"]==211){
			//print_r($files);echo "<br>";
			//}
			$db->exe_update("mx_user",$files,"id='$rsdb[id]'");
		}
		return true;
	}
	else{
		return false;
	}
}

function wx_tongbu_userinfo($next_openid="",$getnum=0){
	global $db;
	if (trim($next_openid)==""){
		$db->excu("update mx_user set istongbu='0'");
	}
	$restr=true;
	$next_openid=trim($next_openid);
	$token=wx_get_token();
	$getstr=post("https://api.weixin.qq.com/cgi-bin/user/get?access_token={$token}&next_openid={$next_openid}", $menustr);
	$getinfo=json_decode($getstr,true);
	if (trim($getinfo["errcode"])==""){
		if (is_array($getinfo["data"]["openid"])){
			foreach ($getinfo["data"]["openid"] as $key =>$value){
				if (trim($value)!=""){
				//更新用户状态
				$haveinfo="";
				$haveinfo=$db->getinfo("select * from mx_user where weixinid='{$value}' limit 1");
				if (is_array($haveinfo)){
					//更新VPP用户
					//wx_update_userinfo($haveinfo["id"]);
					$db->excu("update mx_user set isguanzhu='1',istongbu='1' where weixinid='{$value}'");
				}
				else{
					//新建VPP用户
					$db->excu("insert into mx_user (regdate,isok,weixinid,isguanzhu,guandate) values('".date("Y-m-d H:i:s")."','1','{$value}','1','".date("Y-m-d H:i:s")."')");
					$userid=mysql_insert_id();
					//更新VPP用户信息
					wx_update_userinfo($userid);
				}
				$getnum++;
				}
			}
		}
		if($getnum<$getinfo["count"]){
			wx_tongbu_userinfo($getinfo["next_openid"],$getnum);
			exit();
		}
		$restr=true;
	}
}

function post($url, $jsonData){
	$ch = curl_init($url) ;
	curl_setopt($ch, CURLOPT_URL,$url); 
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_AUTOREFERER, 1); 
	curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch) ;
	curl_close($ch) ;
	return $result;
}


function show_ip($ip){
	$ipstr="";
	if ($ip!=""){
		$iparr=explode(".",$ip);
		$iparr[count($iparr)-1]="*";
		$ipstr=implode(".",$iparr);
	}
	return $ipstr;
}

function get_kuo($string){
	$restr="";
	if ($string!=""){
		$string=strtolower($string);
		$flvurl=explode(".",$string);
		$aaaa=count($flvurl)-1;
		$restr=$flvurl[$aaaa];
	}
	return $restr;
}

function get_flvurl($string){
	global $webdb;
	$restr="";
	if ($string!=""){
		$string=strtolower($string);
		if(substr(trim($string),0,3)=="flv" or substr(trim($string),0,4)=="/flv"){$restr=$webdb[updir].$string;}
		else{$restr=$string;}
	}
	return $restr;
}

function get_face($arr){
	global $webdb;
	$restr="";
	if (is_array($arr)){
		$string2=strtolower($arr["faceurl"]);
		if(substr(trim($string2),0,7)!="http://" and substr(trim($string2),0,1)!="/"){$restr=$webdb[updir].$arr["faceurl"];}
		else{$restr=$arr["faceurl"];}
	}
	return $restr;
}

function get_video($flvurl,$width="",$height=""){
	global $webdb;
	$width=intval($width);
	$height=intval($height);
	if ($width==0){$width=300;}
	if ($height==0){$height=200;}
	$restr="";
	if ($flvurl!=""){
		$kuo=strtolower(get_kuo($flvurl));
		if ($kuo=="flv"){
	  		$flvurl=get_flvurl($flvurl);
			$restr='<OBJECT codeBase=http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0 height='.$height.' width='.$width.' classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000><PARAM NAME="movie" VALUE="/mediaplayer.swf"><PARAM NAME="quality" VALUE="high"><PARAM NAME="menu" VALUE="false"><PARAM NAME="allowFullScreen" VALUE="true"><PARAM NAME="FlashVars" VALUE="vcastr_file='.$flvurl.'&vcastr_title=&LogoUrl=&IsAutoPlay=0&IsContinue=0&LogoText='.$webdbaaa["www_url"].'&logoTextFontSize=26&BufferTime=3"><embed src="/mediaplayer.swf" allowFullScreen="true" menu="false" quality="high" FlashVars="vcastr_file='.$flvurl.'&vcastr_title=&LogoUrl=&IsAutoPlay=0&IsContinue=0&LogoText='.$webdbaaa["www_url"].'&logoTextFontSize=26&BufferTime=3" width='.$width.' height='.$height.' type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></OBJECT>';
		}
		else if (substr($kuo,0,2)=="rm"){
	  		$flvurl=get_flvurl($flvurl);
			$restr='<OBJECT height='.$height.' width='.$width.' classid=clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA VIEWASTEXT><PARAM NAME="_ExtentX" VALUE="0"><PARAM NAME="_ExtentY" VALUE="0"><PARAM NAME="AUTOSTART" VALUE="0"><PARAM NAME="SHUFFLE" VALUE="0"><PARAM NAME="PREFETCH" VALUE="0"><PARAM NAME="NOLABELS" VALUE="0"><PARAM NAME="SRC" VALUE="'.$flvurl.'"><PARAM NAME="CONTROLS" VALUE="Imagewindow,StatusBar,ControlPanel"><PARAM NAME="CONSOLE" VALUE="RAPLAYER"><PARAM NAME="LOOP" VALUE="0"><PARAM NAME="NUMLOOP" VALUE="0"><PARAM NAME="CENTER" VALUE="0"><PARAM NAME="MAINTAINASPECT" VALUE="0"><PARAM NAME="BACKGROUNDCOLOR" VALUE="#000000"></OBJECT><br /><br />此视频必须使用realplayer播放器播放，请先下载组件';			
		}
//		else if (strlen($kuo)>2 and strlen($kuo)<6){
//	  		$flvurl=get_flvurl($flvurl);
//			$restr='<EMBED src="'.$flvurl.'" width='.$width.' height='.$height.' type=audio/x-pn-realaudio-plugin console="Clip1" controls="IMAGEWINDOW,ControlPanel,StatusBar" autostart="true"></EMBED>';			
//		}
		elseif (strtolower(substr($flvurl,0,7))=="http://"){
			$restr='<iframe height='.$height.' width='.$width.' src="'.$flvurl.'" frameborder=0 allowfullscreen></iframe>';																											
		}
		else{
			$restr=dvhtmlcode($flvurl);
		}
		
	}
	return $restr;
}

function get_photourl($string){
	global $webdb;
	$restr="";
	if ($string!=""){
		$string2=strtolower($string);
		if(substr(trim($string2),0,7)!="http://"){
			if (substr(trim($string2),0,1)!="/"){
			$restr=$webdb[weburl].$webdb[updir].$string;
			}
			else{
			$restr=$webdb[weburl].$string;
			}
		}
		else{$restr=$string;}
	}
	else{
		$restr="http://".$webdb[weburl]."/images/nopic.jpg";
	}
	return $restr;
}

function get_photoname($string){
	global $webdb;
	$restr="";
	if ($string!=""){
		$photourl=explode("/",$string);
		$aaaa=count($photourl)-1;
		$restr=$photourl[$aaaa];
	}
	return $restr;
}


function jump($msg,$url,$time=1){
	if($time==0){
	  echo "<script>location.href='$url';</script>";
		//@header("location:$url");exit;
	}else{
		require("location.php");exit;
	}
}
function jump2($msg,$url,$time=1){
	if($time==0){
	  echo "<script>location.href='$url';</script>";
		//@header("location:$url");exit;
	}else{
		require("../../mxsoft/location.php");exit;
	}
}

function url_encode($url){
	if ($url!=""){
		$url=str_replace("?","---",$url);
		$url=str_replace("&","--",$url);
	}
	return $url;
}
function url_code($url){
	if ($url!=""){
		$url=str_replace("---","?",$url);
		$url=str_replace("--","&",$url);
	}
	return $url;
}
//获取二维码
function get_erweima($chl,$widhtHeight='150',$EC_level='L',$margin='0')
{
 $url = urlencode($url); 
 echo '<img src="http://chart.apis.google.com/chart?chs='.$widhtHeight.'x'.$widhtHeight.'&cht=qr&chld='.$EC_level.'|'.$margin.'&chl='.$chl.'" alt="QR code" widhtHeight="'.$size.'" widhtHeight="'.$size.'"/>';
}


//--更新标签---------------------------------------------------------------
function tags_encode($tags){
	$restr="";
	if ($tags!=""){
		$restr="|".str_replace(",","|",$tags)."|";	
	}
	return $restr;
}
function tags_decode($tags){
	$restr="";
	if ($tags!=""){
		$tagsarr=explode("|",$tags);
		if (is_array($tagsarr)){
			foreach ($tagsarr as $key =>$value){
				if ($value!=""){
				if ($restr==""){$restr=$value;}
				else{$restr.=",".$value;}
				}
			}
		}
	}
	return $restr;
}
function tags_decodearr($tags){
	$restr="";
	if ($tags!=""){
		$tagsarr=explode("|",$tags);
		if (is_array($tagsarr)){
			foreach ($tagsarr as $key =>$value){
				if ($value!=""){
				if ($restr==""){$restr[]=$value;}
				}
			}
		}
	}
	return $restr;
}



/**
* 方法:isdate()
* 功能:判断日期格式是否正确
* 参数:$str 日期字符串 $format日期格式
* 返回:布儿值
*/
function isdate($str,$format="Y-m-d"){
	$strArr = explode("-",$str);
	if(empty($strArr)){
		return false;
	}
	foreach($strArr as $val){
		if(strlen($val)<2){
			$val="0".$val;
		}
		$newArr[]=$val;
	}
	$str =implode("-",$newArr);
    $unixTime=strtotime($str);
    $checkDate= date($format,$unixTime);
    if($checkDate==$str)
        return true;
    else
        return false;
}

//每月第一天和最后一天
function getthemonth($date) 
{ 
    if(isdate($date)){
		$firstday = date('Y-m-01', strtotime($date)); 
		$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day")); 
		return array($firstday, $lastday); 
	}else{
		return "";
	}
}
//获取本周第一天和最后一天
function aweek($gdate= "", $first =1){
 if(!$gdate) $gdate = date("Y-m-d");
 
 $w = date("w", strtotime($gdate));
 $dn = $w ? $w - $first : 6;
 $st = date("Y-m-d", strtotime("$gdate -".$dn." days"));
 $en = date("Y-m-d", strtotime("$st +6 days"));
 $last_st = date('Y-m-d',strtotime("$st - 7 days"));
 $last_en = date('Y-m-d',strtotime("$st - 1 days"));
 
 return array($st, $en,$last_st,$last_en);
}

//获取两个日期之间的所有日期
function get_dayarr($startdate,$enddate){
	$restr="";
	if (isdate($startdate) and isdate($enddate)){
		$j=0;
		for($i = strtotime($startdate); $i <strtotime($enddate); $i += 86400) {
			$restr[$j]=date("Y-m-d",$i);
			$j++;
		}
	}
	return $restr;
}

//获得不重复的随机数
function getsui($str=""){
    $sui="";
	rand(1000,10000);
    if ($str!=""){
	    $sui=rand(1000,10000);
	    $strarr=explode(",",$str);
		foreach($strarr as $key =>$value){
		    if ($value==$sui){$sui.=getsui($str);}
		}
	}
	else{$sui=rand(1000,10000);}
	return $sui;
}

/*show_select
数组转换为select中的option
*/
function show_select($arr,$selectid="-"){
    $str="";
    if(is_array($arr)){
	    foreach($arr as $key =>$value){
		    if ("$key"==$selectid){$sel=" selected";}else{$sel="";}
		    $str.='<option value="'.$key.'" '.$sel.'>'.$value.'</option>';
		}
	}
	return $str;
}

/*
show_zidian
获得字典信息生成select
$selectname:生成select表单的名称
$zdname:字典类型名称
$selectid:选中选项值
*/
function show_radio($name,$arr,$checkid="-"){
    $str="";
    if(is_array($arr)){
	    foreach($arr as $key =>$value){
		    if ($key==$checkid){$sel=" checked";}else{$sel="";}
			if ($checkid=="-" and $i==0){$sel=" checked";$i++;}
			$str.='<input type="radio" name="'.$name.'" class="input_check" value="'.$key.'" '.$sel.'>'.$value.'&nbsp;';
		}
	}
	return $str;
}

////////验证码编码函数
function encheckcode($str){
    $str=strtoupper($str);
    $str=base64_encode(substr(md5($str), 1, 10));
	return $str;
}
//计算活跃时间
function  get_timebig($s){
	if (formatdate($s)!=""){
		$he=date("y-m-d h:i:s",strtotime($s));
		$ie=date("y-m-d h:i:s");
		$a=strtotime($ie);
		$b=strtotime($he);
		$day=floor(($a-$b)/(84000));
		$house=floor(($a-$b)/(84000/24));
		$minue=floor(($a-$b)/(84000/24/60));
		if($day>=100){
			return "约100天前";
		}
		elseif($day>=1){
			return "约".$day."天前";
		}
		else if($day<1&&$house>=1){
			return "约".$house."小时前";
		}
		else{
			return  "约".$minue."分钟前";
		}
	}
}
//计算结束天数
function get_endday($date1,$date2) {
	$date1=formatdate($date1);
	$date2=formatdate($date2);
	if ($date1!="" and $date2!=""){
	$Date_List_a1=explode("-",$date1);
	$Date_List_a2=explode("-",$date2);
	$d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]);
	$d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]);
	$Days=round(($d2-$d1)/3600/24);
	$Days=$Days+1;
	}
	return $Days; 
}

//计算百分比
function get_baifenbi($num1=0,$num2=0){
	$restr="";
	$num1=(float)$num1;
	$num2=(float)$num2;
	if ($num1>=$num2){
		$restr[0]="up";
	}
	else{
		$restr[0]="down";
		$num3=$num1;
		$num1=$num2;
		$num2=$num3;
	}
	$add=$num1-$num2;
	if ($num2==0){$restr[1]=$num1*100;}
	else{
		$restr[1]=number_format(($num1-$num2)/$num2*100,2);
	}
	$restr[1].="%";
	return $restr;
}
//formatdate
//格式化日期
function formatdate($str){
    if ($str!=""){
	    $str=date("Y-m-d",strtotime($str));
	}
	if ($str=="1900-1-1" or $str=="1900-01-01" or $str=="1970-1-1" or $str=="1970-01-01" or $str=="1999-11-30"){$str="";}
	return $str;
}
/**
 * 时间戳格式转换
 * @author Tony
 * @param unknown $str
 * @return string
 */
function toDate($str,$format='Y-m-d H:i:s'){
	$result = '';
	if($str){
		$result = date($format,$str);
	}
	return $result;
}

function movefile($oldpic,$pic,$nsite){
if (!file_exists( $nsite)){@mkdir($nsite, 0777);}
}

function get_is_int($id){
		$in=$id;
		if(ereg("([0-9])",$in)){

		}else{
			echo "请输入正确参数！！！";
			exit();
		}
		$id=$in;		
		return($id);
}


function dvhtmlcode($fString){
if (!empty($fString)){
    $fString = str_replace("&gt;", ">",$fString);
    $fString = str_replace( "&lt;", "<",$fString);
    $fString = str_replace("&nbsp;",CHR(32),$fString);
    $fString = str_replace("&quot;",CHR(34),$fString);
    $fString = str_replace("&#39;", CHR(39),$fString);
    $fString = str_replace("<BR>", CHR(10),$fString);
	$fString = str_replace('&quot;','"',$fString);
	$fString = str_replace('&#39;',"'",$fString);
    return $fString;
}
}

function dvhtmlencode($fString){
if (!empty($fString)){
    $fString = str_replace(">", "&gt;",$fString);
    $fString = str_replace("<", "&lt;",$fString);
    $fString = str_replace(CHR(32), "&nbsp;",$fString);
    $fString = str_replace(CHR(9), "&nbsp;",$fString);
    $fString = str_replace(CHR(34), "&quot;",$fString);
    $fString = str_replace(CHR(39), "&#39;",$fString );
    $fString = str_replace(CHR(13), "",$fString);
    $fString = str_replace(CHR(10), "<BR>",$fString);
	$fString = str_replace('"','&quot;',$fString);
	$fString = str_replace("'",'&#39;',$fString);
    return $fString;
}
}

function dvhtmlcode2($fString){
	if (!empty($fString)){
		$fString = dvhtmlcode($fString);
		$fString = strip_tags($fString);
		return $fString;
	}
}


function filtrate($msg){
	$msg = str_replace('&amp;','&',$msg);
	$msg = str_replace('&nbsp;',' ',$msg);
	$msg = str_replace('"','&quot;',$msg);
	$msg = str_replace("'",'&#39;',$msg);
	$msg = str_replace("<","&lt;",$msg);
	$msg = str_replace(">","&gt;",$msg);
	$msg = str_replace("\t","   &nbsp;  &nbsp;",$msg);
	$msg = str_replace("\r","",$msg);
	$msg = str_replace("   "," &nbsp; ",$msg);
	return $msg;
}

function wordscut($str,$len,$luostr="")//字符位置从0开始   
	{   
		$str=strip_tags($str);
		$strlength=$len; 
		if (strlen($str)>$len){
			$tmpstr  =	"";
			for($i=$start;$i<$strlength;$i++){   
				if(ord(substr($str,$i,1))>0xa0){   
					$tmpstr.=substr($str,$i,3);   
					$i++;   
					$i++;   
				}   
				else	
					$tmpstr.=substr($str,$i,1);
			}
			$tmpstr=$tmpstr.$luostr;
			return $tmpstr;  
		}
		else{return $str;} 	
	} 
	
function wordscut2($str,$len,$luostr="")//字符位置从0开始   
	{   
		$str=strip_tags($str);
		$len=intval($len); 
		$lennow=0;
		if (strlen($str)>$len){
			$tmpstr  =	"";
			for($i=0;$i<strlen($str);$i++){
				if(ord(substr($str,$i,1))>0xa0){   
					$tmpstr.=substr($str,$i,3);   
					$i++;
					$i++;
				}   
				else{	
					$tmpstr.=substr($str,$i,1);
				}
				$lennow++;
				if  ($lennow>=$len){break;}
			}
			$tmpstr=$tmpstr.$luostr;
			return $tmpstr;  
		}
		else{return $str;} 	
	} 

//--百度地图-----------------------------------------------------------------------
//通过坐标获取详细地址
function get_maps_addinfo($x,$y){
	$weizhi=file_get_contents("http://api.map.baidu.com/geocoder/v2/?ak=5f5b39083dfc300b6359ce2d85020dea&callback=renderReverse&location=$x,$y&output=xml&pois=0");
	if ($weizhi!=""){
		$weizhiarr=simplexml_load_string($weizhi);
		if ($weizhiarr->status==0){
			$weizhiinfo[status]=$weizhiarr->status;
			$weizhiinfo[lat]=$weizhiarr->result->location->lat;
			$weizhiinfo[lng]=$weizhiarr->result->location->lng;
			$weizhiinfo[address]=$weizhiarr->result->formatted_address;
			$weizhiinfo[business]=$weizhiarr->result->business;
			$weizhiinfo[city]=$weizhiarr->result->addressComponent->city;
			$weizhiinfo[district]=$weizhiarr->result->addressComponent->district;
			$weizhiinfo[province]=$weizhiarr->result->addressComponent->province;
			$weizhiinfo[street]=$weizhiarr->result->addressComponent->street;
			$weizhiinfo[street_number]=$weizhiarr->result->addressComponent->street_number;
		}
		else{
			$weizhiinfo=array(status=>$weizhiarr->status);
		}
	}
	else{
		$weizhiinfo=array(status=>"-1");
	}
	return $weizhiinfo;
}


///////////
class myfunction{
///////////////// 字符串转换//////////
	function str_to($str)
	{
		$str=str_replace("","&nbsp;",$str);
		$str=str_replace("<","&lt;",$str);
		$str=str_replace(">","&gt;",$str);
		$str=nl2br($str);
		return $str;
	}
	
	 

/////////////////////////////////////////url跳转↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

	function popmassage($tishi,$dizhi,$xuhao){
			if($xuhao==""||$xuhao=="popgotourl"){
				echo "<script language=javascript type=text/javascript>";
				echo "alert('".$tishi."');location.href='".$dizhi."';</script>";
				exit();
			}
			if($xuhao=="popback"){
				echo "<script language='JavaScript'>";
				echo "alert('".$tishi."');setTimeout('history.back();',4);</script>";
				exit();
			}
			if($xuhao=="popback2"){
				echo "<script language='JavaScript'>";
				echo "alert('".$tishi."');setTimeout('history.go(-2);',4);</script>";
				exit();
			}
			if($xuhao=="back"){
				echo "<script language='JavaScript'>";
				echo "setTimeout('history.go(-1);',4);</script>";
				exit();
			}
			if($xuhao=="gotourl"){
				echo "<script language=javascript type=text/javascript>";
				echo "location.href='".$dizhi."';</script>";
				exit();
			}
			if($xuhao=="alertgotourl"){
				echo "<script language=javascript type=text/javascript>";
				echo "alert('".$tishi."');location.href='".$dizhi."';</script>";
				exit();
			}
			if($xuhao=="back2"){
				echo "<script language='JavaScript'>";
				echo "setTimeout('history.go(-2);',4);</script>";
				exit();
			}
			if($xuhao=="close"){
				echo "<script language=javascript type=text/javascript>";
				echo "alert('".$tishi."');window.close();</script>";
				exit();
			}
		}


//////////////////////////////url跳转end↑↑↑↑↑↑↑↑↑


}///end class



function SltImageName($ImagesName){
	$TempImagesName=explode(".",$ImagesName);
	$NewImagesName=$TempImagesName[0]."_s.".$TempImagesName[1];
	return $NewImagesName;
}
 function SltImageNameF($ImagesName){
	$TempImagesName=explode("/",$ImagesName);
	$NewImagesName=$TempImagesName[0];
	return $NewImagesName;
}
 function SltImageNameL($ImagesName){
	$TempImagesName=explode("/",$ImagesName);
	$NewImagesName=$TempImagesName[1];
	return $NewImagesName;
}

/**
*写文件函数
**/
function write_file($filename,$data,$method="rb+",$iflock=1){
	@touch($filename);
	$handle=@fopen($filename,$method);
	if($iflock){
		@flock($handle,LOCK_EX);
	}
	@fputs($handle,$data);
	if($method=="rb+") @ftruncate($handle,strlen($data));
	@fclose($handle);
	@chmod($filename,0777);	
	if( is_writable($filename) ){
		return 1;
	}else{
		return 0;
	}
}

	
//更新核心设置缓存
function write_config_cache($webdbs)
{
	global $db,$pre;
	if( is_array($webdbs) )
	{
		foreach($webdbs AS $key=>$value)
		{
			if(is_array($value))
			{
				$webdbs[$key]=$value=implode(",",$value);
			}
			$SQL2.="'$key',";
			$SQL.="('$key', '$value', ''),";
		}
		$SQL=$SQL.";";
		$SQL=str_Replace("'),;","')",$SQL);
		$db->excu(" DELETE FROM mx_config WHERE c_key IN ($SQL2'') ");
		$db->excu(" INSERT INTO `mx_config` VALUES  $SQL ");	
	}
	$writefile="<?php\r\n";
	$query = $db->excu("SELECT * FROM mx_config");
	while($rs = $db->fetch_array($query)){
		if($rs[c_key]=='copyright1'){
			$copyright1=$rs[c_value];
		}elseif($rs[c_key]=='copyright2'){
			$copyright2=$rs[c_value];
		}else{
			$rs[c_value]=addslashes($rs[c_value]);
			$writefile.="\$webdb['$rs[c_key]']='$rs[c_value]';\r\n";
		}
	}
	//write_file(MX_PATH."mx_php/config.php",$writefile);
}

//取得用户可以操作的类型
function Selectadminfid($table,$fid,$ArticleIdPurview,$purview) {
		global $db;
		$query=$db->excu("select fid from $table where fup='$fid' order by list,fid");
		while( @extract($db->fetch_array($query)) ){

		  if ($purview=="true" || strpos("#**#$ArticleIdPurview","|$fid|")>0)
		  {
			$show.=",$fid";
			$show.=Selectadminfid($table,$fid,$ArticleIdPurview,"true");
		  }
		  else
		  { $show.=Selectadminfid($table,$fid,$ArticleIdPurview,"false");}
		}          
		return $show;
}

//栏目列表
function list_allsort($fid,$table='mx_proclass',$toclass="",$prview=""){
	global $db,$lfjdb,$sortdb,$fiddbadmin2,$newsfiddbadmin2,$videofiddbadmin2;
	if ($toclass!=""){$toclassstr=" and class<'$toclass'";}
	if ($table==""){$table="mx_proclass";}
	$query=$db->excu("SELECT * FROM $table where fup='$fid' $toclassstr ORDER BY list,fid");
	while( $rs=$db->fetch_array($query) ){
		$icon="";
		if ($prview=="prview"){
          if (strpos("#**#$fiddbadmin2","|||$rs[fid]|||")>0){
 		    for($i=1;$i<$rs['class'];$i++){
			  $icon.="&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;";
		    }
		    if($icon){
		   	  $icon=substr($icon,0,-24);
			  $icon.="--";
		    }
		    $rs[config]=unserialize($rs[config]);
		    $rs[icon]=$icon;
		    $sortdb[]=$rs;

		    list_allsort($rs[fid],$table,$toclass);
	      }
		  else{list_allsort($rs[fid],$table,$toclass,"prview");}
	   }
	   else{
 		    for($i=1;$i<$rs['class'];$i++){
			  $icon.="&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;";
		    }
		    if($icon){
		   	  $icon=substr($icon,0,-24);
			  $icon.="--";
		    }
		  $rs[config]=unserialize($rs[config]);
		  $rs[icon]=$icon;
		  $sortdb[]=$rs;
	      list_allsort($rs[fid],$table,$toclass);
	   }
	}
}

/**
*更新栏目级别
**/
function mod_sort_class($table,$class,$fid){
	global $db;
	$db->excu("UPDATE $table SET class='$class'+1  WHERE fup='$fid' ");
	$query=$db->excu("SELECT * FROM $table WHERE fup='$fid'");
	while( @extract($db->fetch_array($query)) ){
		mod_sort_class($table,$class,$fid);
	}
}

/**
*更新栏目有几个子栏目
**/
function  mod_sort_sons($table,$fid){
	global $db;
	$query=$db->excu("SELECT * FROM $table WHERE fup='$fid'");
	$sons=$db->num_rows($query);
	$db->excu("UPDATE $table SET sons='$sons' WHERE fid='$fid' ");
	while( @extract($db->fetch_array($query)) ){
		mod_sort_sons($table,$fid);
	}
}

/**
*检查是否误操作.设置子栏目为自己的父栏目
**/
function check_fup($table,$fid,$fup){
	global $db;
	global $fun;
	if(!$fup){
		return ;
	}elseif($fid==$fup){
		showmsg("不能设置自身为父栏目");
	}
	$query = $db->excu("SELECT * FROM $table WHERE fid='$fup'");
	while($rs = $db->fetch_array($query)){
		if($rs[fup]==$fid){
  	      $fun->popmassage("你不能设置本身的子栏目作为父栏目,这是不允许的.但你可以设置其他子栏目作为父栏目！","","popback");
	      exit();
		}elseif($rs[fup]){
			check_fup($table,$fid,$rs[fup]);
		}
	}
}
/**
*上传文件
**/
function upfile($upfile,$array){
	global $db,$lfjuid,$pre,$webdb,$groupdb,$lfjdb;

	$filename=$array[name];
	$array["path"]=str_replace("//","/",$array["path"]);
	$path=makepath(MX_PATH.$array[path]);
	$path=str_replace("\\","/",$path);
	if($path=='false')
	{
		showerr("不能创建目录$array[path]，上传失败",1);
	}
	elseif(!is_writable($path))
	{
		showerr("文件不存在，上传失败",1);
	}

	$size=abs($array[size]);

	$filetype=strtolower(strrchr($filename,"."));

	if(!$upfile)
	{
		showerr("文件不存在，或文件无后缀名,上传失败",1);
	}
	elseif(!$filetype)
	{
			showerr("你所上传的文件格式为:$filetype,而系统仅允许上传的文件格式为:$webdb[upfileType]",1);
	}
	else
	{

       if( !in_array($filetype,explode(" ",$webdb[upfileType])) )
		{
			showerr("你所上传的文件格式为:$filetype,而系统仅允许上传的文件格式为:$webdb[upfileType]",1);
		}


		if( !$groupdb[upfileMaxSize] && $webdb[upfileMaxSize] && ($webdb[upfileMaxSize]*1024)<$size )
		{
			showerr("你所上传的文件大小为:".($size/1024)."K,而系统仅允许上传的文件大小为:{$webdb[upfileMaxSize]}K",1);
		}
	}
	$oldname=preg_replace("/(.*)\.([^.]*)/is","\\1",$filename);
	$tempname="{$lfjuid}_".date("YmdHms_",time()).rand(100,1000).$filetype;
	$newfile="$path/$tempname";

	if(@move_uploaded_file($upfile,$newfile))
	{
		@chmod($newfile, 0777);
		$ck=2;
	}
    if(!$ck)
	{
		if(@copy($upfile,$newfile))
		{
			@chmod($newfile, 0777);
			$ck=2;
		}
	}
	if($ck)
	{
		return $tempname;
	}
	else
	{
		showerr("请检查空间问题,上传失败",1);
	}
}

function upfile_user($upfile,$array){
	global $db,$lfjuid,$pre,$webdb,$groupdb,$lfjdb;

	$filename=$array[name];
	$array["path"]=str_replace("//","/",$array["path"]);
	$path=makepath(MX_PATH.$array[path]);
	if($path=='false')
	{
		showerr("不能创建目录$array[path]，上传失败",1);
	}
	elseif(!is_writable($path))
	{
		showerr("文件不存在，上传失败",1);
	}

	$size=abs($array[size]);

	$filetype=strtolower(strrchr($filename,"."));

	if(!$upfile)
	{
		showerr("文件不存在，或文件无后缀名,上传失败",1);
	}
	elseif(!$filetype)
	{
			showerr("你所上传的文件格式为:$filetype,而系统仅允许上传的文件格式为:$webdb[upfileType]",1);
	}
	else
	{

       if( !in_array($filetype,explode(" ","jpg gif bmp png")) )
		{
			showerr("你所上传的文件格式为:$filetype,而系统仅允许上传的文件格式为:$webdb[upfileType]",1);
		}

		if( !$groupdb[upfileMaxSize] && (10*1024*1024)<$size )
		{
			showerr("你所上传的文件大小为:".($size/1024)."K,而系统仅允许上传的文件大小为:{$webdb[upfileMaxSize]}K",1);
		}
	}
	$oldname=preg_replace("/(.*)\.([^.]*)/is","\\1",$filename);
	$tempname="{$lfjuid}_".date("YmdHms_",time()).rand(100,1000).$filetype;
	$newfile="$path/$tempname";

	if(@move_uploaded_file($upfile,$newfile))
	{
		@chmod($newfile, 0777);
		$ck=2;
	}
    if(!$ck)
	{
		if(@copy($upfile,$newfile))
		{
			@chmod($newfile, 0777);
			$ck=2;
		}
	}
	if($ck)
	{
		return $tempname;
	}
	else
	{
		showerr("请检查空间问题,上传失败",1);
	}
}

/**
*生成目录
**/
function makepath($path){
	//这个\没考虑
	$path=str_replace("//","/",$path);
	$detail=explode("/",$path);
	$syspath=str_replace("\\","/",MX_PATH);
	$syspath=str_replace(":/",":\\",$syspath);
	foreach($detail AS $key=>$value){
		if($value==''&&$key!=0){
			//continue;
		}
		$newpath.="$value/";
		$newpath=str_replace("\\","/",$newpath);
		$newpath=str_replace(":/",":\\",$newpath);
		if((eregi("^\/",$newpath)||eregi(":",$newpath))&&!str_replace($syspath,"",strstr($newpath,$syspath))){continue;}
		if( !is_dir($newpath) ){
			if(mkdir(str_replace("/","\\",$newpath))){
				$result='false';
			}
			chmod(str_replace("/","\\",$newpath),0777);
		}
	}
	if(!$result){
		return $path;
	}
}


/**
*警告页面函数
**/
function showerr($msg,$type=''){
	global $webdb;
		$msg=str_replace("'","\'",$msg);
		echo "<SCRIPT LANGUAGE=\"JavaScript\">
		<!--
		alert('$msg');
		history.back(-1);
		//-->
		</SCRIPT>";
	exit;
}

/**
*取得真实目录
**/
function tempdir($file){
	global $webdb;
	if( ereg("://",$file) )
	{
		return $file;
	}
	else
	{
		return $webdb[www_url]."/".$webdb[updir]."/".$file;
	}
}

// *****生成缩略图*****
// 只考虑jpg,png,gif格式
// $srcImgPath 源图象路径
// $targetImgPath 目标图象路径
// $targetW 目标图象宽度
// $targetH 目标图象高度
function makeThumbnail($srcImgPath,$targetImgPath,$targetW=0,$targetH=0)
{
$imgSize = GetImageSize($srcImgPath);
$imgType = $imgSize[2];
//@ 使函数不向页面输出错误信息
switch ($imgType)
{
case 1:
$srcImg = @ImageCreateFromGIF($srcImgPath);
break;
case 2:
$srcImg = @ImageCreateFromJpeg($srcImgPath);
break;
case 3:
$srcImg = @ImageCreateFromPNG($srcImgPath);
break;
}
//取源图象的宽高
$srcW = ImageSX($srcImg);
$srcH = ImageSY($srcImg);

if($srcW>$targetW || $srcH>$targetH)
{
	$targetX = 0;
	$targetY = 0;
	if ($srcW > $srcH)
	{
	$finaW=$targetW;
	$finalH=round($srcH*$finaW/$srcW);
	$targetY=floor(($targetH-$finalH)/2);
	}
	else
	{
	$finalH=$targetH;
	$finaW=round($srcW*$finalH/$srcH);
	$targetX=floor(($targetW-$finaW)/2);
	}
	//function_exists 检查函数是否已定义
	//ImageCreateTrueColor 本函数需要GD2.0.1或更高版本
	if(function_exists("ImageCreateTrueColor"))
	{
	$targetImg=ImageCreateTrueColor($targetW,$targetH);
	}
	else
	{
	$targetImg=ImageCreate($targetW,$targetH);
	}
	$targetX=($targetX<0)?0:$targetX;
	$targetY=($targetX<0)?0:$targetY;
	$targetX=($targetX>($targetW/2))?floor($targetW/2):$targetX;
	$targetY=($targetY>($targetH/2))?floor($targetH/2):$targetY;
	//背景白色
	//$white = ImageColorAllocate($targetImg, 255,255,255);
	ImageFilledRectangle($targetImg,0,0,$targetW,$targetH,$white);
	/*
	PHP的GD扩展提供了两个函数来缩放图象：
	ImageCopyResized 在所有GD版本中有效，其缩放图象的算法比较粗糙，可能会导致图象边缘的锯齿。
	ImageCopyResampled 需要GD2.0.1或更高版本，其像素插值算法得到的图象边缘比较平滑，
	该函数的速度比ImageCopyResized慢。
	*/
	if(function_exists("ImageCopyResampled"))
	{
	ImageCopyResampled($targetImg,$srcImg,$targetX,$targetY,0,0,$finaW,$finalH,$srcW,$srcH);
	}
	else
	{
	ImageCopyResized($targetImg,$srcImg,$targetX,$targetY,0,0,$finaW,$finalH,$srcW,$srcH);
	}
	switch ($imgType) {
	case 1:
	ImageGIF($targetImg,$targetImgPath);
	break;
	case 2:
	ImageJpeg($targetImg,$targetImgPath);
	break;
	case 3:
	ImagePNG($targetImg,$targetImgPath);
	break;
	}
	ImageDestroy($srcImg);
	ImageDestroy($targetImg);
}
else //不超出指定宽高则直接复制
{
	copy($srcImgPath,$targetImgPath);
	ImageDestroy($srcImg);
}
}


/**
 * 生成缩略图
 * @author yangzhiguo0903@163.com
 * @param string     源图绝对完整地址{带文件名及后缀名}
 * @param string     目标图绝对完整地址{带文件名及后缀名}
 * @param int        缩略图宽{0:此时目标高度不能为0，目标宽度为源图宽*(目标高度/源图高)}
 * @param int        缩略图高{0:此时目标宽度不能为0，目标高度为源图高*(目标宽度/源图宽)}
 * @param int        是否裁切{宽,高必须非0}
 * @param int/float  缩放{0:不缩放, 0<this<1:缩放到相应比例(此时宽高限制和裁切均失效)}
 * @return boolean
 */
function img2thumb($src_img, $dst_img, $width = 150, $height = 150, $cut = 0, $proportion = 0)
{
    if(!is_file($src_img))
    {
        return false;
    }
    $ot = fileext($dst_img);
    $otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
    $srcinfo = getimagesize($src_img);
    $src_w = $srcinfo[0];
    $src_h = $srcinfo[1];
    $type  = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
    $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);
 
    $dst_h = $height;
    $dst_w = $width;
    $x = $y = 0;
 
    /**
     * 缩略图不超过源图尺寸（前提是宽或高只有一个）
     */
    if(($width> $src_w && $height> $src_h) || ($height> $src_h && $width == 0) || ($width> $src_w && $height == 0))
    {
        $proportion = 1;
    }
    if($width> $src_w)
    {
        $dst_w = $width = $src_w;
    }
    if($height> $src_h)
    {
        $dst_h = $height = $src_h;
    }
 
    if(!$width && !$height && !$proportion)
    {
        return false;
    }
    if(!$proportion)
    {
        if($cut == 0)
        {
            if($dst_w && $dst_h)
            {
                if($dst_w/$src_w> $dst_h/$src_h)
                {
                    $dst_w = $src_w * ($dst_h / $src_h);
                    $x = 0 - ($dst_w - $width) / 2;
                }
                else
                {
                    $dst_h = $src_h * ($dst_w / $src_w);
                    $y = 0 - ($dst_h - $height) / 2;
                }
            }
            else if($dst_w xor $dst_h)
            {
                if($dst_w && !$dst_h)  //有宽无高
                {
                    $propor = $dst_w / $src_w;
                    $height = $dst_h  = $src_h * $propor;
                }
                else if(!$dst_w && $dst_h)  //有高无宽
                {
                    $propor = $dst_h / $src_h;
                    $width  = $dst_w = $src_w * $propor;
                }
            }
        }
        else
        {
            if(!$dst_h)  //裁剪时无高
            {
                $height = $dst_h = $dst_w;
            }
            if(!$dst_w)  //裁剪时无宽
            {
                $width = $dst_w = $dst_h;
            }
            $propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
            $dst_w = (int)round($src_w * $propor);
            $dst_h = (int)round($src_h * $propor);
            $x = ($width - $dst_w) / 2;
            $y = ($height - $dst_h) / 2;
        }
    }
    else
    {
        $proportion = min($proportion, 1);
        $height = $dst_h = $src_h * $proportion;
        $width  = $dst_w = $src_w * $proportion;
    }
 
    $src = $createfun($src_img);
    $dst = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
    $white = imagecolorallocate($dst, 255, 255, 255);
    imagefill($dst, 0, 0, $white);
 
    if(function_exists('imagecopyresampled'))
    {
        imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
    }
    else
    {
        imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);

    }
    $otfunc($dst, $dst_img);
    imagedestroy($dst);
    imagedestroy($src);
    return true;
}

function fileext($file)
{
    return pathinfo($file, PATHINFO_EXTENSION);
}
function DeleteHtml($str){ 
   $str = trim($str); 
  $str = strip_tags($str,""); 
  $str = ereg_replace("\t","",$str); 
  $str = ereg_replace("\r\n","",$str); 
  $str = ereg_replace("\r","",$str); 
  $str = ereg_replace("\n","",$str); 
  $str = ereg_replace(" "," ",$str); 
  return trim($str); 
} 

function mkdirs($dir) { 
    if(!is_dir($dir)) { 
        if(!mkdirs(dirname($dir))){ 
            return false; 
        }
        if(!mkdir($dir,0777)){
            return false; 
        }
    }
     return true;
}

/**
 * 发放积分
 * @author Tony
 * @param unknown $targetid	目标id
 * @param unknown $userid 用户id
 */
function giveIntegral($userid,$integral,$intro,$tier=3){
	global $db;
	$share_db = 'mx_share';
	if($userid){
		//积分增加
		addIntegral($integral, $userid, $intro);
		//是否从用户分享来
		$targetuserid = $db->getsingle("select targetuserid from $share_db where userid=$userid");
		//如果是从用户分享来，递归
		if($targetuserid && $tier>1){
			$newIntegral = $integral/2;
			$tier--;
			giveIntegral($targetuserid,$newIntegral,$intro,$tier);
		}
	}
}

/**
 * 积分记录
 * @param unknown $integral 积分数
 * @param unknown $userid 用户id
 * @param unknown $intro  获取简介
 * @param unknown $type 积分类型：1：获得，2：消费
 */
function addIntegral($integral,$userid,$intro,$type=1){
	global $db;
	$user_db = 'mx_app_user';
	$user_integral_db = 'mx_app_user_integral';
	if($type==1){
		$db->excu("update $user_db set integral=integral+$integral where id=$userid");
	}elseif($type==2){
		$db->excu("update $user_db set integral=integral-$integral where id=$userid");
	}
	$integral_insert_fields['userid'] = $userid;
	$integral_insert_fields['integral'] = $integral;
	$integral_insert_fields['type'] = $type;
	$integral_insert_fields['intro'] = $intro;
	$integral_insert_fields['createtime'] = time();
	$db->exe_insert($user_integral_db, $integral_insert_fields);
}

/**
* 发送post请求
* @author Tony
* @param string $url 请求地址
* @param array $post_data post键值对数据
* @return string
*/
function send_post($url, $post_data) {
	$postdata = http_build_query($post_data);
	$options = array(
			'http' => array(
					'method' => 'POST',
					'header' => 'Content-type:application/x-www-form-urlencoded',
					'content' => $postdata,
					'timeout' => 15 * 60 // 超时时间（单位:s）
			)
	);
	$context = stream_context_create($options);
	$result = file_get_contents($url, false, $context);
	return $result;
}
?>